<template>
  <NDrawer v-model:show="visible" :width="900" title="稽查结果">
    <NDrawerContent closable>
      <NSpin :show="loading">
        <NSpace vertical :size="16">
          <!-- 统计信息 -->
          <NCard title="稽查统计" size="small">
            <NGrid :cols="4" :x-gap="12">
              <NGridItem>
                <NStatistic label="总记录数" :value="result?.totalCount || 0" />
              </NGridItem>
              <NGridItem>
                <NStatistic label="问题记录数" :value="result?.problemCount || 0" />
              </NGridItem>
              <NGridItem>
                <NStatistic label="问题率" :value="problemRate" suffix="%" />
              </NGridItem>
              <NGridItem>
                <NStatistic label="执行时长" :value="result?.executionTime || 0" suffix="ms" />
              </NGridItem>
            </NGrid>
          </NCard>

          <!-- 问题分布图表 -->
          <NCard title="问题分布" size="small">
            <div ref="chartRef" style="width: 100%; height: 300px"></div>
          </NCard>

          <!-- 问题详情 -->
          <NCard title="问题详情" size="small">
            <NDataTable
              :columns="problemColumns"
              :data="result?.problemDetails || []"
              size="small"
              :max-height="400"
              :pagination="{ pageSize: 10 }"
            />
          </NCard>
        </NSpace>
      </NSpin>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { fetchCheckTaskDetail } from '@/service/api';

interface Props {
  visible: boolean;
  taskId: number;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  taskId: 0
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const emit = defineEmits<Emits>();

const visible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
});

const loading = ref(false);
const result = ref<any>(null);
const chartRef = ref<HTMLElement>();
let chartInstance: ECharts | null = null;

const problemRate = computed(() => {
  if (!result.value || !result.value.totalCount) return 0;
  return ((result.value.problemCount / result.value.totalCount) * 100).toFixed(2);
});

const problemColumns = [
  { key: 'rowId', title: '记录ID', width: 100 },
  { key: 'ruleName', title: '违反规则', width: 150 },
  { key: 'problemDesc', title: '问题描述', minWidth: 200 },
  { key: 'fieldName', title: '问题字段', width: 120 },
  { key: 'fieldValue', title: '字段值', width: 150 }
];

async function loadResult() {
  if (!props.taskId) return;
  loading.value = true;
  try {
    const res = await fetchCheckTaskDetail(props.taskId);
    result.value = res.data.lastResult || {
      totalCount: 0,
      problemCount: 0,
      executionTime: 0,
      problemDetails: [],
      dimensionStats: {}
    };
    await nextTick();
    renderChart();
  } finally {
    loading.value = false;
  }
}

function renderChart() {
  if (!chartRef.value || !result.value) return;

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const dimensionStats = result.value.dimensionStats || {};
  const data = Object.entries(dimensionStats).map(([name, value]) => ({
    name,
    value
  }));

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '问题分布',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  chartInstance.setOption(option);
}

watch(visible, val => {
  if (val) {
    loadResult();
  } else {
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  }
});
</script>

<style scoped></style>
